/**
 * 
 */
package services;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import model.Contact;

/**
 * @author e412596
 * 
 */
public class ParserContacts {
    private static Pattern contactPattern = Pattern.compile("[A-z]+.[A-z]+");
    private static Pattern phonePattern = Pattern.compile("([0-9]+)");
    private static Pattern nextelPattern = Pattern.compile("[0-9]+.[0-9]+");
    private static final String cabecera = "First Name,Home Phone,Home Phone 2,Mobile Phone\r\n";

    /**
     * e412596
     * @param file
     * @return Contact
     */
    public Contact parse(File file) {
        Contact c = null;
        try {
            BufferedReader in = new BufferedReader(new FileReader(file));
            List < String > str = new ArrayList < String >();
            while (in.ready()) {
                String line = in.readLine();
                if (!line.trim().isEmpty())
                    str.add(line);
            }
            in.close();
            // System.out.println(str);

            String combinedLine = str.get(1) + " " + (str.size() > 2 ? str.get(2): "");
             System.out.println(combinedLine);
            c = extractContact(combinedLine);
             System.out.println(c);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return c;
    }

    /**
     * e412596
     * @param fileLine
     * @return Contact
     */
    private Contact extractContact(String fileLine) {
        Contact contact = new Contact();

        Matcher contactMatcher = contactPattern.matcher(fileLine);
        Matcher phoneMatcher = phonePattern.matcher(fileLine);
        Matcher nextelMatcher = nextelPattern.matcher(fileLine);

        StringBuilder name = new StringBuilder();
        while (contactMatcher.find()) {
            name.append(contactMatcher.group() + " ");
        }
        contact.setName(name.toString().trim().replaceAll("\\W\\s", ""));

        while (phoneMatcher.find()) {
            String phone = phoneMatcher.group();
            if (phone.length() > 7 && phone.length()<13) {
                contact.addPhone(phoneMatcher.group());
            }
        }

        while (nextelMatcher.find()) {
            String nextel = nextelMatcher.group();
            if (contact.getPhone() == null
                    || !contact.getPhone().contains(nextel.trim())) {
                contact.setNextel(nextel);
            }
        }
        contact.setOriginalLine(fileLine);
        return contact;
    }

    public void printContactsFile(Collection < Contact > contacts, String path)
            throws IOException {

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path
                + "\\contacts.csv")));
        writer.append(cabecera);

        int length = cabecera.split(",").length;

        for (Contact contact : contacts) {
            if (!(contact.getName() == null || contact.getName().trim()
                    .isEmpty())) {
                String[] line = new String[length];
                line[0] = contact.getName();

                int i = 1;
                if (contact.getPhone() != null && !contact.getPhone().isEmpty()) {
                    while (i <= contact.getPhone().size()) {
//                        System.out.println(contact);
                        line[i] = contact.getPhone().get(i-1);
                        i++;
                    }
                }
                if (contact.getNextel() != null
                        && !contact.getNextel().trim().isEmpty()) {
                    line[i] = contact.getNextel();
                }

                String printLine = "";
                for (String str : line) {
                    if (str == null) {
                        str = "";
                    }
                    printLine = printLine.concat(str.concat(","));
                }
                printLine = printLine.substring(0, printLine.length() - 1)
                        + "\r";
                // System.out.println(contact);
                // System.out.println(printLine);
                writer.append(printLine);
            }
        }
        writer.flush();
        writer.close();
    }
}
